<template>
  <div class="events">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card>
          <h3>筛选条件</h3>
          <el-form>
            <el-form-item label="演出名称">
              <el-input
                v-model="filters.search"
                placeholder="搜索演出名称"
                prefix-icon="el-icon-search"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="分类">
              <el-select v-model="filters.category" placeholder="请选择">
                <el-option label="全部" value=""></el-option>
                <el-option label="演唱会" value="concert"></el-option>
                <el-option label="话剧" value="drama"></el-option>
                <el-option label="体育" value="sports"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="城市">
              <el-select v-model="filters.city" placeholder="请选择">
                <el-option label="全部" value=""></el-option>
                <el-option label="北京" value="beijing"></el-option>
                <el-option label="上海" value="shanghai"></el-option>
                <el-option label="广州" value="guangzhou"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleFilterChange">筛选</el-button>
              <el-button @click="resetFilters">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-table :data="filteredEvents" style="width: 100%">
          <el-table-column prop="title" label="演出名称" width="200" />
          <el-table-column prop="date" label="日期" width="120" />
          <el-table-column prop="venue" label="场馆" width="150" />
          <el-table-column prop="city" label="城市" width="100" />
          <el-table-column prop="price" label="价格" width="100">
            <template #default="scope">
              <el-tag type="danger">¥{{ scope.row.price }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" @click="viewDetail(scope.row.id)">详情</el-button>
              <el-button size="small" type="primary" @click="addToCart(scope.row)">购票</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          style="margin-top: 20px; justify-content: center;"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '../store'
import { ElMessage } from 'element-plus'
import api from '../api'

export default {
  name: 'Events',
  setup() {
    const router = useRouter()
    const store = useAppStore()
    const events = ref([])
    const loading = ref(false)
    
    const filters = ref({
      search: '',
      category: '',
      city: ''
    })

    const currentPage = ref(1)
    const pageSize = 10
    const total = ref(0)
    const categories = ref([])
    const cities = ref([])

    // 从API获取事件列表
    const fetchEvents = async (page = 1, category = '', city = '', search = '') => {
      loading.value = true
      try {
        const params = {
          page,
          page_size: pageSize,
          category,
          city,
          search
        }
        
        const response = await api.get('/events', { params })
        
        // 处理API响应（后端直接返回事件数组）
        if (Array.isArray(response)) {
          events.value = response
          total.value = response.length
        } else {
          console.error('Unexpected response format:', response)
          events.value = []
          total.value = 0
        }
        
        // 提取唯一的分类和城市列表
        extractCategoriesAndCities()
      } catch (error) {
        console.error('Failed to fetch events:', error)
        ElMessage.error('获取演出列表失败')
        events.value = []
        total.value = 0
      } finally {
        loading.value = false
      }
    }
    
    // 从事件数据中提取分类和城市列表
    const extractCategoriesAndCities = () => {
      const categorySet = new Set()
      const citySet = new Set()
      
      events.value.forEach(event => {
        if (event.category) categorySet.add(event.category)
        if (event.city) citySet.add(event.city)
      })
      
      categories.value = Array.from(categorySet)
      cities.value = Array.from(citySet)
    }

    const filteredEvents = computed(() => {
      let filtered = events.value
      
      // 按名称搜索
      if (filters.value.search.trim()) {
        const searchQuery = filters.value.search.toLowerCase().trim()
        filtered = filtered.filter(event => 
          event.title.toLowerCase().includes(searchQuery)
        )
      }
      
      // 按分类筛选
      if (filters.value.category) {
        filtered = filtered.filter(event => event.category === filters.value.category)
      }
      
      // 按城市筛选
      if (filters.value.city) {
        filtered = filtered.filter(event => event.city === filters.value.city)
      }
      
      return filtered
    })

    const viewDetail = (id) => {
      router.push(`/events/${id}`)
    }

    const addToCart = (event) => {
      store.addToCart(event)
      ElMessage.success('已添加到购物车')
    }
    
    // 处理筛选条件变化
    const handleFilterChange = () => {
      currentPage.value = 1
      fetchEvents(1, filters.value.category, filters.value.city, filters.value.search)
    }
    
    // 重置筛选条件
    const resetFilters = () => {
      filters.value = {
        search: '',
        category: '',
        city: ''
      }
      currentPage.value = 1
      fetchEvents()
    }
    
    // 处理页面变化
    const handlePageChange = (page) => {
      currentPage.value = page
      fetchEvents(page, filters.value.category, filters.value.city, filters.value.search)
    }
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchEvents()
    })

    return {
      events,
      filters,
      currentPage,
      pageSize,
      total,
      filteredEvents,
      loading,
      categories,
      cities,
      viewDetail,
      addToCart,
      handleFilterChange,
      handlePageChange,
      resetFilters
    }
  }
}
</script>